package com.sec.typhoondatapush.controller;

import com.sec.typhoondatapush.entity.JobConfig;
import com.sec.typhoondatapush.entity.Response;
import com.sec.typhoondatapush.enums.ConfigEnum;
import com.sec.typhoondatapush.repository.JobConfigRepository;
import com.sec.typhoondatapush.service.QuartzTableService;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.quartz.CronScheduleBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 动态修改定时任务
 *
 * @author zhuwq
 * @version V1.0
 * @date Create in  2018/7/30- 15:11
 */
@RestController
@Slf4j
public class QuartzController {

    @Autowired
    private JobConfigRepository jobConfigRepository;

    @Autowired
    private QuartzTableService quartzTableService;

    @GetMapping("/table")
    public String table() {
        ModelMap map = new ModelMap();
        List<JobConfig> jobConfigs = jobConfigRepository.findAll();
        for (JobConfig jobConfig : jobConfigs) {
            String message = ConfigEnum.findByMessage(jobConfig.getStatus());
            jobConfig.setStatus(message);
        }
        map.put("configs", jobConfigs);
        return map.toString();
    }

    @PostMapping("/updateStatus")
    public Response updateStatus(@RequestParam(value = "id") ObjectId id,
                                 @RequestParam(value = "status") String status) {
        Response response = new Response();
        response.setResult(false);
        try {
            quartzTableService.updateStatus(id, status);
            response.setResult(true);
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setMsg(e.toString());
        }
        return response;
    }

    @PostMapping("/updateCron")
    public Response updateCron(@RequestParam(value = "id") ObjectId id,
                               @RequestParam(value = "cron") String cron) {

        Response response = new Response();
        response.setResult(false);
        try {
            CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(cron);
            response.setResult(true);
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setMsg("cron表达式有误！！");
            return response;
        }
        try {
            quartzTableService.updateCron(id, cron);
            response.setResult(true);
        } catch (Exception e) {
            response.setMsg(e.toString());
        }
        return response;
    }
}
